<template>
	<view class="address-container">
		<!-- 自定义导航栏 - 小程序适配版本 -->
		<view class="custom-navbar" :style="navbarStyle">
			<view class="navbar-content" :style="navbarContentStyle">
				<view class="back-btn" @tap.stop="goBack">
					<u-icon name="arrow-left" size="20" color="#fff"></u-icon>
				</view>
				<view class="navbar-title">
					<text class="title-text">收货地址</text>
				</view>
			</view>
		</view>
		
		<!-- 地址列表 -->
		<view class="address-list">
			<view 
				v-for="item in addressList" 
				:key="item.id" 
				class="address-item"
				@click="selectAddress(item)"
			>
				<!-- 地址信息 -->
				<view class="address-info">
					<view class="user-info">
						<text class="name">{{ item.name }}</text>
						<text class="phone">{{ item.telephone }}</text>
					</view>
					<text class="address-detail">{{ item.location }} {{ item.address }}</text>
				</view>
				
				<!-- 操作按钮 -->
				<view class="address-actions">
					<view class="action-item" @click.stop="setDefault(item)">
						<u-icon 
							:name="item.is_default ? 'checkmark-circle-fill' : 'checkmark-circle'" 
							:color="item.is_default ? '#27B387' : '#c8c9cc'" 
							size="18"
						></u-icon>
						<text class="action-text">设为默认地址</text>
					</view>
					<view class="action-item" @click.stop="editAddress(item)">
						<u-icon name="edit-pen" color="#666" size="16"></u-icon>
						<text class="action-text">编辑</text>
					</view>
					<view class="action-item" @click.stop="deleteAddress(item)">
						<u-icon name="trash" color="#ff6b6b" size="16"></u-icon>
						<text class="action-text">删除</text>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view v-if="addressList.length === 0" class="empty-state">
				<u-icon name="map" size="60" color="#c8c9cc"></u-icon>
				<text class="empty-text">暂无收货地址</text>
				<text class="empty-tip">点击下方按钮添加地址</text>
			</view>
		</view>
		
		<!-- 新增地址按钮 -->
		<view class="add-address-btn">
			<u-button 
				type="primary" 
				@click="addAddress"
				:custom-style="buttonStyle"
			>
				新增地址
			</u-button>
		</view>
		
		<!-- 加载状态 -->
		<u-loading-page 
			:loading="loading"
			loading-text="加载中..."
		></u-loading-page>
	</view>
</template>

<script>
import api from '@/api/index.js'

export default {
	data() {
		return {
			// 小程序适配相关
			statusBarHeight: 0,
			navBarHeight: 44,
			menuButtonInfo: {
				width: 0,
				height: 0,
				top: 0,
				right: 0,
				bottom: 0,
				left: 0
			},
			windowWidth: 375,
			// 原有数据
			addressList: [],
			loading: false,
			// 来源页面参数
			fromParams: null
		}
	},
	
	onLoad(options) {
		this.initMiniProgramAdapt()
		// 解析来源页面参数
		if (options.data) {
			try {
				let dataStr = options.data
				// 尝试解码，如果已经是解码后的字符串，decodeURIComponent 不会报错
				try {
					dataStr = decodeURIComponent(dataStr)
				} catch (e) {
					// 如果解码失败，使用原始字符串
					dataStr = options.data
				}
				// 检查是否是有效的 JSON 字符串
				if (dataStr && typeof dataStr === 'string' && (dataStr.startsWith('{') || dataStr.startsWith('['))) {
					this.fromParams = JSON.parse(dataStr)
					console.log('接收到的参数:', this.fromParams)
				} else {
					// 如果不是 JSON 格式，可能是简单的字符串参数
					this.fromParams = { from: dataStr }
				}
			} catch (error) {
				console.error('解析参数失败:', error)
				// 解析失败时，尝试作为简单参数处理
				if (options.from) {
					this.fromParams = { from: options.from }
				}
			}
		} else if (options.from) {
			// 如果没有 data 参数，检查是否有 from 参数
			this.fromParams = { from: options.from }
		}
		
		// 加载地址列表
		this.loadAddressList()
	},
	
	computed: {
		navbarStyle() {
			return {
				paddingTop: this.statusBarHeight + 'px'
			}
		},
		navbarContentStyle() {
			const paddingRight = (this.menuButtonInfo.width || 0) + (this.menuButtonInfo.right || 0) - this.windowWidth + 10
			return {
				height: this.navBarHeight + 'px',
				paddingRight: paddingRight + 'px'
			}
		},
		buttonStyle() {
			return 'width: 100%; height: 88rpx; border-radius: 44rpx; background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%); border: none;'
		}
	},
	
	methods: {
		// 小程序适配初始化
		initMiniProgramAdapt() {
			// 获取系统信息
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight || 0
			this.windowWidth = systemInfo.windowWidth || 375

			// 获取胶囊按钮信息（仅小程序）
			// #ifdef MP
			try {
				this.menuButtonInfo = uni.getMenuButtonBoundingClientRect() || {
					width: 87,
					height: 32,
					top: this.statusBarHeight + 6,
					right: 7,
					bottom: this.statusBarHeight + 38,
					left: this.windowWidth - 94
				}
				this.navBarHeight = this.menuButtonInfo.height + (this.menuButtonInfo.top - this.statusBarHeight) * 2
			} catch (e) {
				console.error('获取胶囊按钮信息失败:', e)
				this.menuButtonInfo = {
					width: 87,
					height: 32,
					top: this.statusBarHeight + 6,
					right: 7,
					bottom: this.statusBarHeight + 38,
					left: this.windowWidth - 94
				}
				this.navBarHeight = 44
			}
			// #endif

			// #ifndef MP
			this.menuButtonInfo = {
				width: 0,
				height: 0,
				top: 0,
				right: 0,
				bottom: 0,
				left: 0
			}
			// #endif
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 加载地址列表
		async loadAddressList() {
			try {
				this.loading = true
				
				const result = await api.addressApi.getAddressList()
				
				this.loading = false
				
				if (result.r === 0) {
					this.addressList = result.data.ual || []
					
					// 如果只有一个地址，自动设为默认
					if (this.addressList.length === 1 && !this.addressList[0].is_default) {
						await this.setDefaultAddress(this.addressList[0], true)
					}
				} else {
					uni.showToast({
						title: result.msg || '获取地址列表失败',
						icon: 'none'
					})
				}
			} catch (error) {
				this.loading = false
				console.error('加载地址列表失败:', error)
				uni.showToast({
					title: '网络异常，请重试',
					icon: 'none'
				})
			}
		},
		
		// 选择地址（从确认订单页面跳转过来时）
		selectAddress(item) {
			if (this.fromParams && this.fromParams.from === 'confirmOrder') {
				// 保存选中的地址到缓存
				const addressData = {
					id: item.id,
					name: item.name,
					phone: item.telephone,
					detail: `${item.location} ${item.address}`
				}
				
				uni.setStorageSync('selectedAddress', addressData)
				
				// 返回确认订单页面
				uni.navigateBack()
			}
		},
		
		// 设置默认地址
		async setDefault(item) {
			try {
				const newDefaultStatus = !item.is_default
				
				const result = await this.setDefaultAddress(item, newDefaultStatus)
				
				if (result) {
					// 更新本地数据
					this.addressList.forEach(addr => {
						if (addr.id === item.id) {
							addr.is_default = newDefaultStatus ? 1 : 0
						} else if (newDefaultStatus) {
							addr.is_default = 0
						}
					})
					
					uni.showToast({
						title: newDefaultStatus ? '已设为默认地址' : '已取消默认地址',
						icon: 'success'
					})
				}
			} catch (error) {
				console.error('设置默认地址失败:', error)
				uni.showToast({
					title: '操作失败，请重试',
					icon: 'none'
				})
			}
		},
		
		// 设置默认地址API调用
		async setDefaultAddress(item, isDefault) {
			try {
				const result = await api.addressApi.editAddress({
					id: item.id,
					name: item.name,
					telephone: item.telephone,
					province_id: item.province_id,
					city_id: item.city_id,
					district_id: item.district_id,
					location: item.location,
					address: item.address,
					is_default: isDefault ? 1 : 0
				})
				
				return result.r === 0
			} catch (error) {
				console.error('设置默认地址API调用失败:', error)
				return false
			}
		},
		
		// 编辑地址
		editAddress(item) {
			// 保存要编辑的地址信息到缓存
			uni.setStorageSync('editAddressData', item)
			
			uni.navigateTo({
				url: `/pages/address/edit?id=${item.id}&isDefault=${item.is_default}`
			})
		},
		
		// 删除地址
		deleteAddress(item) {
			uni.showModal({
				title: '温馨提示',
				content: '是否删除当前地址？',
				confirmText: '确定',
				cancelText: '取消',
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({ title: '删除中...' })
							
							const result = await api.addressApi.deleteAddress({
								ids: item.id
							})
							
							uni.hideLoading()
							
							if (result.r === 0) {
								// 从列表中移除
								this.addressList = this.addressList.filter(addr => addr.id !== item.id)
								
								// 清除缓存中的编辑地址数据
								const editData = uni.getStorageSync('editAddressData')
								if (editData && editData.id === item.id) {
									uni.removeStorageSync('editAddressData')
								}
								
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})
							} else {
								uni.showToast({
									title: result.msg || '删除失败',
									icon: 'none'
								})
							}
						} catch (error) {
							uni.hideLoading()
							console.error('删除地址失败:', error)
							uni.showToast({
								title: '网络异常，请重试',
								icon: 'none'
							})
						}
					}
				}
			})
		},
		
		// 新增地址
		addAddress() {
			uni.navigateTo({
				url: '/pages/address/edit'
				// url: '/pages/my/address-edit'
			})
		}
	},
	
	// 页面显示时刷新列表
	onShow() {
		console.log('============show')
		// 如果从编辑页面返回，重新加载列表
		const shouldRefresh = uni.getStorageSync('shouldRefreshAddressList')
		if (shouldRefresh) {
			uni.removeStorageSync('shouldRefreshAddressList')
			this.loadAddressList()
		}
	}
}
</script>

<style lang="scss" scoped>
/* 容器样式 */
.address-container {
	background-color: #f8f8f8;
	height: 100vh;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	padding-bottom: 120rpx;
	box-sizing: border-box;
}

.address-list {
	padding: 30rpx 20rpx 20rpx;
	flex: 1;
	overflow-y: auto;
	margin-top: 150rpx;
}

/* 地址项样式 */
.address-item {
	background-color: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	transition: transform 0.2s ease;

	&:active {
		transform: scale(0.98);
	}
}

.address-info {
	margin-bottom: 30rpx;
}

.user-info {
	display: flex;
	align-items: center;
	margin-bottom: 15rpx;
}

.name {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	margin-right: 30rpx;
}

.phone {
	font-size: 28rpx;
	color: #666;
}

.address-detail {
	font-size: 26rpx;
	color: #666;
	line-height: 1.5;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	line-clamp: 2;
	overflow: hidden;
}

/* 操作按钮样式 */
.address-actions {
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-top: 1rpx solid #f0f0f0;
	padding-top: 20rpx;
}

.action-item {
	display: flex;
	align-items: center;
	flex: 1;
	justify-content: center;
	padding: 10rpx;
	transition: background-color 0.2s ease;

	&:active {
		background-color: #f5f5f5;
		border-radius: 8rpx;
	}

	&:first-child .action-text {
		color: #333;
	}

	&:last-child .action-text {
		color: #ff6b6b;
	}
}

.action-text {
	font-size: 24rpx;
	color: #666;
	margin-left: 8rpx;
}

/* 空状态样式 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 40rpx;
	text-align: center;
}

.empty-text {
	font-size: 32rpx;
	color: #666;
	margin: 30rpx 0 10rpx;
}

.empty-tip {
	font-size: 26rpx;
	color: #999;
}

/* 底部按钮 */
.add-address-btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 20rpx 30rpx;
	border-top: 1rpx solid #e5e5e5;
	z-index: 100;
}

/* 导航栏样式 */
.custom-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background: linear-gradient(135deg, #FF8033 0%, #FF6B35 100%);
}

.custom-navbar .navbar-content {
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	position: relative;
}

.custom-navbar .back-btn {
	width: 64rpx;
	height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	z-index: 10;
}

.custom-navbar .navbar-title {
	position: absolute;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	pointer-events: none;
}

.custom-navbar .navbar-title .title-text {
	font-size: 40rpx;
	font-weight: 600;
	color: #fff;
	letter-spacing: 1rpx;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
	.address-item {
		padding: 20rpx;
	}

	.name {
		font-size: 28rpx;
	}

	.phone {
		font-size: 26rpx;
	}

	.address-detail {
		font-size: 24rpx;
	}
}
</style>